package com.hpq.common.utils;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;
import java.util.Optional;

@Component
@Slf4j
public class JwtUtils {
    // jwt密钥
    @Value("${coffeechat.jwt.secret}")
    private String secret;
    private static final String UID_CLAIM = "uid";
    private static final String CREATE_CLAIM = "createTime";
    /**
     * jwt生成token
     * <p>
     * 构成：header . payload . signature
     */
    public  String createToken(Long uid) {
        String token = JWT.create()
                .withClaim(UID_CLAIM, uid)
                .withClaim(CREATE_CLAIM, new Date())
                .sign(Algorithm.HMAC256(secret));
        return token;
    }

    /**
     *验证并解密token
     * @param token
     * @return
     */
    public Map<String, Claim> verifyToken(String token){
        if(StringUtils.isEmpty(token)){
            return null;
        }
        // 创建验证对象
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(secret)).build();
       // 验证并解密token
        DecodedJWT verify = verifier.verify(token);
        return verify.getClaims();
    }

    /**
     * 根据token获取uid
     * @param token
     * @return
     */
    public Long getUidByToken(String token){
        return Optional.ofNullable(verifyToken(token))
                .map(map->map.get(UID_CLAIM))
                .map(Claim::asLong)
                .orElse(null);
    }
}
